<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\admin\model\Activity;
use app\admin\model\StoreShop;
use app\common\controller\Backend;
use PhpZip\Exception\ZipException;
use PhpZip\ZipFile;
use think\Config;
use think\Db;
use think\Exception;
use think\Session;

/**
 * 控制台
 *
 * @icon fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{
    protected $Version="1.2.4";
    /**
     * 查看
     */
    public function index()
    {  //dump( $Version);exit();

        $data1 = $this->statistics();

       $version=json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/version'), true);
        $this->view->assign('localVersion',$this->Version);
       if(isset($version['data'])&&$this->auth->id == get_addon_config('douyin')['super_id'])
       {

           $this->view->assign('version',$version['data']);
       }

        $seventtime = \fast\Date::unixtime('day', -7);
        $paylist = $createlist = [];
        for ($i = 0; $i < 7; $i++)
        {
            $day = date("Y-m-d", $seventtime + ($i * 86400));
            $createlist[$day] = mt_rand(20, 200);
            $paylist[$day] = mt_rand(1, mt_rand(1, $createlist[$day]));
        }
        $hooks = config('addons.hooks');
        $uploadmode = isset($hooks['upload_config_init']) && $hooks['upload_config_init'] ? implode(',', $hooks['upload_config_init']) : 'local';
        $addonComposerCfg = ROOT_PATH . '/vendor/karsonzhang/fastadmin-addons/composer.json';
        Config::parse($addonComposerCfg, "json", "composer");
        $config = Config::get("composer");
        $addonVersion = isset($config['version']) ? $config['version'] : __('Unknown');

        if ($this->auth->id != get_addon_config('douyin')['super_id']) {
            $child = model('Admin')->getAgentChild($this->auth->id,'shop_id');
            if ($child) {
                $map['manystore_id'] = ['in',$child];
            } else {
                $shop_id = Session::get("admin")['shop_id'];
                $map['manystore_id'] = $shop_id;
            }
                $totaluser=(new User())->where($map)->count();
                $totalshop=0;
                $totalactivity=(new Activity())->where($map)->count();
                $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
                $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                $map['createtime'] = array('between', array($beginToday,$endToday));


                $totaluser_day=(new User())->where($map)->count();
                $totalshop_day=0;
                $totalacti_day=(new Activity())->where($map)->count();
            }
        else
        {
            $totaluser=(new User())->count();
            $totalshop=(new StoreShop())->count();
            $totalactivity=(new Activity())->count();

            $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            $map['createtime'] = array('between', array($beginToday,$endToday));

            $totaluser_day=(new User())->where($map)->count();
            $totalshop_day=(new StoreShop())->where($map)->count();
            $totalacti_day=(new Activity())->where($map)->count();



        }


        $this->view->assign([
            'totaluser'        => $totaluser,
            'totalshop'       => $totalshop,
            'totalactivity'       => $totalactivity,
         /*   'totalorderamount' => 174800,
            'todayuserlogin'   => 321,*/
       /*     'todayusersignup'  => 430,
            'todayorder'       => 2324,
            'unsettleorder'    => 132,
            'sevendnu'         => '80%',
            'sevendau'         => '32%',*/
            'totaluser_day'          => $totaluser_day,
            'totalshop_day'       => $totalshop_day,
            'totalacti_day'       => $totalacti_day,
           /* 'uploadmode'       => $uploadmode*/
            'data1' => $data1,
        ]);

        return $this->view->fetch();
    }

    public function upgrade()
    {

        $ids =  $this->request->param('id');
        $version=json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/version'), true);

        if(isset($version['data']))
        {

          $versions= $version['data'];
          foreach ($versions as $v)
          {
              if($v['id']==$ids)
              {

                  $temp_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'download';
                  if (!is_dir($temp_path)) {
                      $dirres = mkdir($temp_path, 0700);
                      if (!$dirres) {
                          $this->error('无法自动创建缓存目录！请手动创建:' . $temp_path);
                      }
                  }
                  $file_name=$temp_path . DS ."install".".zip";
                  $file_sql=$temp_path . DS ."install".".sql";

                  file_put_contents($file_name, $this->curl_file_get_contents($v['downloadurl']));
                  file_put_contents($file_sql, $this->curl_file_get_contents($v['sql']));


                  self::importsql($file_sql);
                  self::importfile($file_name);
                  $this->success("升级成功,请清除缓存刷新");
              }

          }

        }


    }






    public static function importsql($sqlFile)
    {

        if (is_file($sqlFile)) {
            $lines = file($sqlFile);
            $templine = '';
            foreach ($lines as $line) {
                if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*') {
                    continue;
                }

                $templine .= $line;
                if (substr(trim($line), -1, 1) == ';') {
                    $templine = str_ireplace('__PREFIX__', config('database.prefix'), $templine);
                    $templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);

                    try {
                        Db::getPdo()->exec($templine);
                    } catch (\PDOException $e) {
                        //$e->getMessage();
                    }
                    $templine = '';
                }
            }
        }
        return true;
    }

    public static function importfile($sqlFile)
    {

        // 打开插件压缩包
        $zip = new ZipFile();
        try {
            $zip->openFile($sqlFile);
        } catch (ZipException $e) {
            $zip->close();
            throw new Exception('Unable to open the zip file');
        }

        //$dir = self::getAddonDir($name);
     /*   if (!is_dir($dir)) {
            @mkdir($dir, 0755);
        }*/

        // 解压插件压缩包
        try {
            $zip->extractTo(ROOT_PATH);
        } catch (ZipException $e) {
            throw new Exception('Unable to extract the file');
        } finally {
            $zip->close();
        }
        return true;
    }





    protected  function  curl_file_get_contents($durl){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $durl);
        curl_setopt($ch, CURLOPT_TIMEOUT, 100);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_SSLVERSION,3);
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }


    //统计数据
    protected function statistics()
    {
        //如果缓存中有数据，则使用缓存的数据
        if ($data = cache('dashboard_statistics')) return $data;

        //获取当前登录用户信息
        $dbPrefix = config('database.prefix');
        $userInfo = Db::table($dbPrefix . 'admin')->alias('admin')
            ->join($dbPrefix . 'auth_group_access admin_group', 'admin_group.uid=admin.id', 'left')
            ->find($this->auth->id);

        //根据用户所属的分组，来确定用户管理的所有商户
        $shopIdData = array();
        if ($userInfo['group_id'] === 1) {
            //登录的账号属于管理员组，则统计所有商户
            $shopIdData = Db::table($dbPrefix . 'store_shop')->column('id');
        } else if ($userInfo['group_id'] === 2) {
            //登录的账号属于商户组，则统计属于该用户的所有商户
            $shopIdData = Db::table($dbPrefix . 'store_shop')->where('admin_id', $userInfo['id'])->column('id');
        } else if ($userInfo['group_id'] === 3) {
            //登录的账号属于代理组，则统计这个代理树的所有商户
            $adminData = Db::table($dbPrefix . 'admin')->field('id,pid')->select();
            $adminIdData = getPosterityId($adminData, $this->auth->id);
            array_push($adminIdData, $this->auth->id);
            if ($adminIdData) $shopIdData = Db::table($dbPrefix . 'store_shop')->where('admin_id', 'in', $adminIdData)->column('id');
        }

        $lastDayStartDate = date('Y-m-d', strtotime('-1 day'));
        $lastDayEndDate = date('Y-m-d 23:59:59', strtotime('-1 day'));
        $lastDayStartTimestamp = strtotime($lastDayStartDate);
        $lastDayEndTimestamp = strtotime($lastDayEndDate);

        $whereTime = array();
        $whereTime['createtime'] = array('between', array($lastDayStartTimestamp, $lastDayEndTimestamp));

        $data = array();
        $data['lastDayNewUser'] = 0;
        $data['lastDayCode'] = 0;
        $data['lastDayUsedCode'] = 0;
        $data['lastDayTotalPlay'] = 0;
        $data['activityRank'] = array();

        $activityIdData = array();
        if ($shopIdData) {
            //根据用户管理的所有商户，来确定所有商户下面所有的活动
            $activityIdData = Db::table($dbPrefix . 'activity')->where('manystore_id', 'in', $shopIdData)->column('id');

            //昨日总新增会员
            $data['lastDayNewUser'] = Db::table($dbPrefix . 'user')
                ->where($whereTime)
                ->where('manystore_id', 'in', $shopIdData)
                ->count();
        }

        if ($activityIdData) {
            $whereTimeAndId = $whereTime;
            $whereTimeAndId['activity_id'] = array('in', $activityIdData);

            //昨日总领券数
            $data['lastDayCode'] = Db::table($dbPrefix . 'seller_code')
                ->where($whereTimeAndId)
                ->count();

            //昨日总核销数
            $data['lastDayUsedCode'] = Db::table($dbPrefix . 'seller_code')
                ->where($whereTimeAndId)
                ->where('status', 1)
                ->count();

            //昨日总播放量
            $data['lastDayTotalPlay'] = Db::table($dbPrefix . 'seller_log')
                ->where($whereTimeAndId)
                ->sum('total_play');

            //活动排名
            $whereId = $whereTimeAndId;
            unset($whereId['createtime']);
            //活动播放量排名前几名
            $data['activityRank'] = Db::table($dbPrefix . 'seller_log')
                ->where($whereId)
                ->field('activity_id,sum(total_play) as sum_total_play')
                ->group('activity_id')
                ->order('sum_total_play desc')
                ->limit(10)
                ->select();
            foreach ($data['activityRank'] as $k => $v) {
                //活动总领券数
                $data['activityRank'][$k]['seller_code'] = Db::table($dbPrefix . 'seller_code')
                    ->where('activity_id', $v['activity_id'])
                    ->count();

                //活动总核销数
                $data['activityRank'][$k]['seller_code_used'] = Db::table($dbPrefix . 'seller_code')
                    ->where('activity_id', $v['activity_id'])
                    ->where('status', 1)
                    ->count();

                //活动信息
                $activityInfo = Db::table($dbPrefix . 'activity')->find($v['activity_id']);
                $data['activityRank'][$k]['activity_name'] = $activityInfo['title'];

                //商户信息
                $shopInfo = Db::table($dbPrefix . 'store_shop')->find($activityInfo['manystore_id']);
                $data['activityRank'][$k]['shop_name'] = $shopInfo['name'];
                $data['activityRank'][$k]['shop_logo'] = $shopInfo['logo'];
            }
        }

        //缓存统计数据
        //cache('dashboard_statistics', $data, 600);
        return $data;
    }

}
